//
//  WHRPTDetailsVC.m
//  AnXin100
//
//  Created by 天质弘耕 on 2018/11/27.
//  Copyright © 2018 tzhg. All rights reserved.
//

#import "WHRPTDetailsVC.h"
#import "YXIgnoreHeaderTouchAndRecognizeSimultaneousTableView.h"
#import "YXTabView.h"
#import "YX.h"

#import "AXspellCell.h"
#import "AXspellFirstCell.h"

#import "AXspellFirstModel.h"
#import "AXHdzqTgModel.h"
#import "AXspellModel.h"

#import "UIViewController+HBD.h"
#import "ConfirmOrderViewController.h"


@interface WHRPTDetailsVC ()<UITableViewDelegate,UITableViewDataSource>


@property (nonatomic, strong) YXIgnoreHeaderTouchAndRecognizeSimultaneousTableView *tableView;

@property (nonatomic, assign) BOOL isTopIsCanNotMoveTabView;

@property (nonatomic, assign) BOOL isTopIsCanNotMoveTabViewPre;

@property (nonatomic, assign) BOOL canScroll;

/** 在拼团人数 */
@property (nonatomic , strong) UILabel * nameLabel;


@property (nonatomic , strong) AXHdzqTgModel *tgModel;
@property (nonatomic , strong) NSMutableArray<AXspellModel *> *modelsArray;
@property (nonatomic , strong) AXspellFirstModel *dataModel1;
@property(nonatomic,strong)NSMutableArray *isOpenArr;

@property (nonatomic, strong) NSString *shopId;

@end

@implementation WHRPTDetailsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.hbd_barTintColor = [UIColor whiteColor];
    self.hbd_barShadowHidden = YES;
    [self initUI];
    [self setupNavigationItems];
    
    ZX_WEAK_SELF
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadNewData];
    }];
    
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    //上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadMoreData];
    }];
    
    
    self.isOpenArr=[[NSMutableArray alloc] init];
    
    
    for (int i = 0; i < 2; i++) {
        NSString*  state=@"close";
        [self.isOpenArr addObject:state];
        
    }
    
}


#pragma mark 下拉刷新的方法
- (void)loadNewData
{
    [self requestCommanderList];
    [self requestgoodsDetail];
    // 刷新表格
//    [self.tableView reloadData];
    // 拿到当前的下拉刷新控件，结束刷新状态
//    [self.tableView.mj_header endRefreshing];
    
}

#pragma mark 上拉加载更多数据
- (void)loadMoreData
{
    // 刷新表格
//    [self.tableView reloadData];
    // 拿到当前的上拉刷新控件，结束刷新状态
//    [self.tableView.mj_footer endRefreshing];
    
}


- (void)setupNavigationItems {
    
    self.hbd_barTintColor = [UIColor whiteColor];
    self.hbd_barShadowHidden = YES;
    
    //返回按钮
    UIButton *kfBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [kfBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    kfBtn.frame = CGRectMake(0, 0, 30, 30);
    [kfBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:kfBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    /** title */
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    titleLabel.text = @"拼团详情";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = FONT_EIGHTEEN;
    titleLabel.textColor = [UIColor colorWithHex:0x29b566];
    self.navigationItem.titleView = titleLabel;
    
}

- (void)backAction:(UIBarButtonItem *)item {
    
    [self.navigationController popViewControllerAnimated:YES];
}



-(void)initUI{

    _tableView = [[YXIgnoreHeaderTouchAndRecognizeSimultaneousTableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)-kBottomBarHeight) style:UITableViewStylePlain];
    
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.delegate = self;
    [self.tableView registerClass:[AXspellFirstCell class] forCellReuseIdentifier:[AXspellFirstCell reuseID]];
    [self.tableView registerClass:[AXspellCell class] forCellReuseIdentifier:[AXspellCell reuseID]];
    _tableView.dataSource = self;
    _tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
    
//    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 250)];
//    headView.backgroundColor = [UIColor clearColor];
//    _tableView.tableHeaderView = headView;
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:kLeaveTopNotificationName object:nil];
}

-(void)acceptMsg : (NSNotification *)notification{
    //NSLog(@"%@",notification);
    NSDictionary *userInfo = notification.userInfo;
    NSString *canScroll = userInfo[@"canScroll"];
    if ([canScroll isEqualToString:@"1"]) {
        _canScroll = YES;
    }
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma MARK - tableviewdelegate & tabviewDatasource

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    if (section == 1) {
        
        UIView*  sectionBackView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
        sectionBackView.backgroundColor=[UIColor whiteColor];
        UIImageView*  lineImageView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 49, SCREEN_WIDTH, 1)];
        [lineImageView setImage:[UIImage imageNamed:@"Google模糊灰.png"]];
        [sectionBackView addSubview:lineImageView];
        
        self.nameLabel=[[UILabel alloc] initWithFrame:CGRectMake(20, 0, SCREEN_WIDTH/2, 50)];
        self.nameLabel.textColor = COLOR_GREEN;
        self.nameLabel.font = FONT_FOURTEEN;
        self.nameLabel.text= @"22人正在拼团";
        [sectionBackView addSubview:self.nameLabel];
        
        UIButton*  button=[UIButton buttonWithType:UIButtonTypeCustom];
        [button setFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
        button.tag=100+section;
        [button addTarget:self action:@selector(ClickSection:) forControlEvents:UIControlEventTouchUpInside];
        [sectionBackView addSubview:button];
        
        
        UIImageView* stateImage=[[UIImageView alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width-30, 20, 20, 10)];
        if ([[_isOpenArr objectAtIndex:section] isEqualToString:@"open"]) {
            [stateImage setImage:[UIImage imageNamed:@"sectionOpen"]];
        }
        
        
        else if ([[_isOpenArr objectAtIndex:section] isEqualToString:@"close"]) {
            [stateImage setImage:[UIImage imageNamed:@"sectionClose"]];
        }
        [sectionBackView addSubview:stateImage];
        return sectionBackView;
    }
    
    else {
        
        return 0;
        
    }
    
    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        
        return 50;
    }
    
    else {
        
        return 0;
        
    }
    
    
}


-(void)ClickSection:(UIButton*)sender
{
    NSString*  state=[self.isOpenArr objectAtIndex:sender.tag-100];
    if ([state isEqualToString:@"open"]) {
        state=@"close";
    }else
    {
        state=@"open";
    }
    self.isOpenArr[sender.tag-100]=state;
    NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:sender.tag-100];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
}





- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 1) {
        
        NSString * state=[self.isOpenArr objectAtIndex:section];
        
        if ([state isEqualToString:@"open"]) {
            
            
            return self.modelsArray.count;
        }
        return 0;
        
    }
    
    else {
        
        return 1;
        
    }
}

/** 行高 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSInteger section = indexPath.section;
    CGFloat height = 0.;
    if (section==0) {
        
        height = 260.;
    }else if(section==1){
        height = 90.;
    }else if(section==2){
        height = CGRectGetHeight(self.view.frame)-kBottomBarHeight-kTopBarHeight;
    }
    return height;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSInteger section  = indexPath.section;
    
    if (section==0) {
        
        AXspellFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:[AXspellFirstCell reuseID] forIndexPath:indexPath];
        
        if (self.dataModel1) {
            cell.model = self.dataModel1;
        }
        /** 取消cell的选中效果 */
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        
        return cell;
        
    }else if(section==1){
        
        AXspellCell  *cell = [tableView dequeueReusableCellWithIdentifier:[AXspellCell reuseID] forIndexPath:indexPath];
        cell.model = self.modelsArray[indexPath.row];
        
        cell.tapCelllickedBlock = ^(NSInteger index) {
            
            ConfirmOrderViewController *vc = [[ConfirmOrderViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
            
        };
        
        
        return cell;
        
    
    }else if(section==2){
        
        NSArray *tabConfigArray = @[@{
                                        @"title":@"详情",
                                        @"view":@"WHRTGDetail",
                                        @"data":@"图文介绍的数据",
                                        @"position":@0
                                        },@{
                                        @"title":@"评论",
                                        @"view":@"WHRTGComment",
                                        @"data":@"商品详情的数据",
                                        @"position":@1
                                        }];
        YXTabView *tabView = [[YXTabView alloc] initWithTabConfigArray:tabConfigArray];
        if (_goodsId != nil) {
            tabView.shopAryId = @[_goodsId, _goodsId];
        }
        [cell.contentView addSubview:tabView];
    }
    return cell;
}



#pragma mark - requestNetwork

//网络请求

- (void)requestgoodsDetail {
    
    
    MBProgressHUD *hud = [WHRNetwork showHudAtView:self.view message:@"正在加载..." isTextOnly:NO];
    ZX_WEAK_SELF
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"groupAcId"] = self.acId;
    
    [NetWorkHelp yl_postDataWith:params url:URL_SPLIT(URL_ActivityPrefecture, URL_ActivityPrefecture_getGroupActivity) success:^(id respose) {
        if ([respose[@"header"][@"statusCode"] integerValue] == 200) {
            
            weakSelf.dataModel1 = [AXspellFirstModel mj_objectWithKeyValues:respose[@"body"][@"groupActivityDetailVO"]];
            [self.tableView reloadData];
            
            
        } else if ([respose[@"header"][@"statusCode"] integerValue] != 200) {
            
           
        }
        [hud hideAnimated:YES];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        
    } failure:^(NSError *error) {
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
    
    
}

//请求团长列表
- (void)requestCommanderList {
    
    MBProgressHUD *hud = [WHRNetwork showHudAtView:self.view message:@"正在加载..." isTextOnly:NO];
    ZX_WEAK_SELF
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"groupAcId"] = self.acId;
    params[@"pageNum"] = @0;
    
    [NetWorkHelp yl_postDataWith:params url:URL_SPLIT(URL_ActivityPrefecture, URL_ActivityPrefecture_getGroupFounderListAtGroupDetail) success:^(id respose) {
        if ([respose[@"header"][@"statusCode"] integerValue] == 200) {
            
            weakSelf.modelsArray = [AXspellModel mj_objectArrayWithKeyValuesArray:respose[@"body"][@"groupFounderSingleVOs"]];
         
             [self.tableView reloadData];
            
        } else if ([respose[@"header"][@"statusCode"] integerValue] != 200) {
            
        }
        [hud hideAnimated:YES];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
    } failure:^(NSError *error) {
        
        
        
    }];
    
    
}



-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat tabOffsetY = [_tableView rectForSection:2].origin.y-kTopBarHeight;
    CGFloat offsetY = scrollView.contentOffset.y;
    _isTopIsCanNotMoveTabViewPre = _isTopIsCanNotMoveTabView;
    if (offsetY>=tabOffsetY) {
        scrollView.contentOffset = CGPointMake(0, tabOffsetY);
        _isTopIsCanNotMoveTabView = YES;
    }else{
        _isTopIsCanNotMoveTabView = NO;
    }
    if (_isTopIsCanNotMoveTabView != _isTopIsCanNotMoveTabViewPre) {
        if (!_isTopIsCanNotMoveTabViewPre && _isTopIsCanNotMoveTabView) {
            //NSLog(@"滑动到顶端");
            [[NSNotificationCenter defaultCenter] postNotificationName:kGoTopNotificationName object:nil userInfo:@{@"canScroll":@"1"}];
            _canScroll = NO;
        }
        if(_isTopIsCanNotMoveTabViewPre && !_isTopIsCanNotMoveTabView){
            //NSLog(@"离开顶端");
            if (!_canScroll) {
                scrollView.contentOffset = CGPointMake(0, tabOffsetY);
            }
        }
    }
}



#pragma mark - getter & setter


-(NSMutableArray<AXspellModel *> *)modelsArray{
    
    if (!_modelsArray) {
        _modelsArray = [NSMutableArray<AXspellModel *> array];
    }
    return _modelsArray;
    
}





@end
